package com.seaboxdata.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author
 * @create 2020-08-25 10:40
 **/
@Slf4j
public class HttpUtil {
    public static String postXMLWithUrlConn(String url,String xmlStr){
        URL urlObj =null;
        HttpURLConnection conn=null;
        String retStr="";
        DataOutputStream dos=null;
        BufferedReader reader=null;
        try {
            urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestProperty("Content-Type", "application/soap+xml;charset=utf-8");
            conn.setRequestProperty("SOAPAction","");
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.write(xmlStr.getBytes("utf-8"));
            dos.flush();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer strBuf = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                strBuf.append(line);
            }
            retStr = strBuf.toString();
        } catch (Exception e) {
            log.error("HttpUtil.postXMLWithUrlConn:fail to http"+e);
        }finally {
            try {
                if(dos!=null) dos.close();
                if(reader!=null) reader.close();
            } catch (Exception e2) { }
        }
        log.info("http result:" + retStr);
        return retStr;
    }

}
